package com.cloudbroker.bcs.platform.ltb.common.ext.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域请求处理
 * */
@Component
public class SimpleCORSFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;

    /**
     * “*”：表示设置允许所有的其他站点跨域请求该
     * “http:http://localhost:63342”：设置只允许指定站点访问该地址
     * ——授权控制
     */
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    //response.setHeader("Access-Control-Allow-Origin", "http://localhost:63342");
    //允许访问的方式，值得注意的是如何这里不设置OPTIONS，那么在web.xml的dispatchservlet的配置里面一定要设置OPTIONS为true，
    //不然仍然不可以实现跨域
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    //允许接下来的60秒之内都可以支持该站点的跨域访问——授权时间
    response.setHeader("Access-Control-Max-Age", "60");
    //控制哪些header能发送真正的请求 
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type,Accept,accessToken,Authorization");
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
}